﻿using System;
using System.Web.UI;
using EPiServer.Core;
using EPiServer.DynamicContent;
using EPiServer.SpecializedProperties;
using ImageStoreNET;
using ImageStoreNET.Developer;
using ImageStoreNET.Developer.Core;
using ImageStoreNET.Developer.Security;
using EPiServer.Municipality.Configuration;

namespace EPiServer.Municipality.Templates.DynamicContent
{
    public partial class DynamicImage : UserControlBase, IDynamicContent
    {
        /* *******************************************************************
         * Properties
         * *******************************************************************/
        #region public string Image
        /// <summary>
        /// Get/Sets the Image of the DynamicImage
        /// </summary>
        /// <value></value>
        public string Image
        {
            get { return (string)Properties["ImageDynamicContent"].Value; }
            set { Properties["ImageDynamicContent"].Value = value; }
        }
        #endregion
        #region public string Description
        /// <summary>
        /// Get/Sets the Description of the DynamicImage
        /// </summary>
        /// <value></value>
        public string Description
        {
            get
            {
                if (Properties["ImageDescriptionDynamicContent"] != null)
                {
                    return (string)Properties["ImageDescriptionDynamicContent"].Value;
                }
                return String.Empty;
            }
            set { Properties["ImageDescriptionDynamicContent"].Value = value; }
        }
        #endregion
        #region public string Photographer
        /// <summary>
        /// Gets the Photographer of the DynamicImage
        /// </summary>
        /// <value></value>
        public string Photographer
        {
            get
            {
                var image = IVFileData.Parse(Image, IVAccessLevel.IgnoreAccess);
                if (image.MetaData != null && image.MetaData[Constants.PhotographerMetaData] != null)
                    return image.MetaData[Constants.PhotographerMetaData].Value;
                return String.Empty;
            }
        }
        #endregion
        #region public String ImagePosition
        /// <summary>
        /// Get/Sets the ImagePosition of the DynamicImage
        /// </summary>
        /// <value></value>
        public String ImagePosition
        {
            get
            {
                if (Properties["ImagePositionDynamicContent"] != null)
                {
                    return (string)Properties["ImagePositionDynamicContent"].Value;
                }
                return String.Empty;
            }
            set { Properties["ImagePositionDynamicContent"].Value = value; }
        }
        #endregion
        #region public String ImageWidth
        /// <summary>
        /// Get/Sets the ImageWidth of the DynamicImage
        /// </summary>
        /// <value></value>
        public String ImageWidth
        {
            get
            {
                if (Properties["ImageWidthDynamicContent"] != null)
                {
                    return (string)Properties["ImageWidthDynamicContent"].Value;
                }
                return String.Empty;
            }
            set { Properties["ImageWidthDynamicContent"].Value = value; }
        }
        #endregion
        #region public bool EnableImageEnlargement
        /// <summary>
        /// Get/Sets the EnableImageEnlargement of the DynamicImage
        /// </summary>
        /// <value></value>
        public bool EnableImageEnlargement
        {
            get
            {
                if (Properties["EnableEnlargmentDynamicContent"] != null && Properties["EnableEnlargmentDynamicContent"].Value != null)
                {
                    return (bool)Properties["EnableEnlargmentDynamicContent"].Value;
                }
                return false;
            }
            set { Properties["EnableEnlargmentDynamicContent"].Value = value; }
        }
        #endregion
        #region public bool RendersWithControl
        /// <summary>
        /// Gets the RendersWithControl of the DynamicImage
        /// </summary>
        /// <value></value>
        public bool RendersWithControl
        {
            get { return true; }
        }
        #endregion
        #region public PropertyDataCollection Properties
        /// <summary>
        /// Gets the Properties of the DynamicTeaser
        /// </summary>
        /// <value></value>
        public PropertyDataCollection Properties
        {
            get
            {
                return _properties;
            }
        }
        private readonly PropertyDataCollection _properties = new PropertyDataCollection();
        #endregion
        #region public string State
        /// <summary>
        /// Get/Sets the State of the DynamicTeaser
        /// </summary>
        /// <value></value>
        public string State
        {
            get
            {
                string imageDescription = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Description ?? String.Empty));
                return Image + "|" + imageDescription + "|" + ImagePosition + "|" + ImageWidth + "|" + EnableImageEnlargement;
            }
            set
            {
                try
                {
                    string[] values = value.Split('|');
                    Image = values[0];
                    Description = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(values[1]));
                    ImagePosition = values[2];
                    ImageWidth = values[3];
                    if (values.Length == 5)
                        EnableImageEnlargement = Boolean.Parse(values[4]);
                    // ReSharper disable EmptyGeneralCatchClause
                }
                catch { }
                // ReSharper restore EmptyGeneralCatchClause
            }
        }
        #endregion
        #region public string CssClass
        /// <summary>
        /// Gets the CssClass of the DynamicImage
        /// </summary>
        /// <value></value>
        public string CssClass
        {
            get
            {
                var cssClass = String.Empty;
                if (ImagePosition != null)
                {
                    cssClass = " " + ImagePosition;
                    if (ImageWidth == "115")
                    {
                        cssClass += " small";
                    }
                }
                return cssClass;
            }
        }
        #endregion
        #region public int Width
        /// <summary>
        /// Gets the Width of the DynamicImage
        /// </summary>
        /// <value></value>
        public int Width
        {
            get
            {
                if (ImagePosition == null)
                {
                    return 582;
                }
                int width;
                return Int32.TryParse(ImageWidth, out width) ? width : 230;
            }
        }
        #endregion
        /* *******************************************************************
         * Constructors
         * *******************************************************************/
        #region public DynamicImage()
        /// <summary>
        /// 
        /// Initializes a new instance of the <b>DynamicTeaser</b> class.
        /// </summary>
        public DynamicImage()
        {
            _properties.Add("ImageDynamicContent", new ImageType());
            _properties.Add("ImageDescriptionDynamicContent", new PropertyString());
            _properties.Add("ImagePositionDynamicContent", new PropertyAppSettings());
            _properties.Add("ImageWidthDynamicContent", new PropertyAppSettings());
            _properties.Add("EnableEnlargmentDynamicContent", new PropertyBoolean());
        }
        #endregion
        /* *******************************************************************
         * Methods
         * *******************************************************************/
        #region public string Render(PageBase hostPage)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hostPage"></param>
        /// <returns></returns>
        public string Render(PageBase hostPage)
        {
            throw new NotImplementedException();
        }
        #endregion
        #region public Control GetControl(PageBase hostPage)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hostPage"></param>
        /// <returns></returns>
        public Control GetControl(PageBase hostPage)
        {
            var control = (DynamicImage)hostPage.LoadControl("~/Templates/DynamicContent/DynamicImage.ascx");
            control.Image = Image;
            control.Description = Description;
            control.ImagePosition = ImagePosition;
            control.ImageWidth = ImageWidth;
            control.EnableImageEnlargement = EnableImageEnlargement;
            return control;
        }
        #endregion
        #region protected override void OnLoad(EventArgs e)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ImageDynamicContent.InnerProperty = new ImageType { Value = Image };
            ImageDynamicContent.DataBind();
            if (!String.IsNullOrEmpty(Description))
            {
                ImageDescriptionLiteral.Text = "<span>" + Description + "</span>";
            }
            if (!String.IsNullOrEmpty(Photographer))
            {
                ImagePhotographerLiteral.Text = String.Format("<span>{0}: {1}</span>", Translate("/municipality/units/dynamicimage/photographer"), Photographer);
            }
            if (EnableImageEnlargement)
            {
                try
                {
                    var builder = IVUrlBuilder.ParseUrl(Image);
                    builder.Height = 600;
                    builder.Width = 800;
                    ImageLink.NavigateUrl = builder.ToString();
                    ImageLink.Visible = true;

                    IVFileData ivFile = IVDataFactory.GetFile(builder.Id, IVAccessLevel.IgnoreAccess);
                    liEnlargeAltText.Text = "<img src=\"/images/zoom.png\" alt=\"" + String.Format(Translate("/municipality/masterpage/enlarge"), ivFile.Title) + "\" />";
                    ImageLink.ToolTip = String.Format(Translate("/municipality/masterpage/enlarge"), ivFile.Title);
                    // ReSharper disable EmptyGeneralCatchClause
                }
                catch { }
                // ReSharper restore EmptyGeneralCatchClause
            }
        }
        #endregion
    } 
}